#include "FPCH.h"

#include "FFamily.h"

#include "FFace.h"
#include "FMetrics.h"
#include "FLoader.h"

namespace Font
{

	Family::Family(Library* a_Library, const tb::String& a_Name)
	{
		m_Library = a_Library;

		m_Name = a_Name;
	}
	
	Family::~Family()
	{
		for (std::vector<Face*>::iterator it = m_Faces.begin(); it != m_Faces.end(); )
		{
			delete *it;
			it = m_Faces.erase(it);
		}
	}

	FaceHandle* Family::GetFaceHandle(unsigned int a_Size, unsigned int a_Style, CharMap* a_Map /*= NULL*/)
	{
		Face* match = NULL;

		for (size_t i = 0; i < m_Faces.size(); i++)
		{
			Metrics* check = m_Faces[i]->GetMetrics();

			if (check->CheckMatchStyle(a_Style & FMASK_STYLE))
			{
				if (a_Style & FSETTING_WEIGHT_SENSITIVE)
				{
					if (check->CheckMatchStyle(a_Style & FMASK_WEIGHT))
					{
						match = m_Faces[i];
						break;
					}
				}
				else
				{
					match = m_Faces[i];
				}
			}
		}

		if (!match) { return NULL; }

		/*if (!match) 
		{
			if (!m_Faces[0]) { return NULL; }

			Metrics* metrics = m_Faces[0]->GetLoader()->CreateMetrics(
				this, 
				a_Style & (FMASK_STYLE | FMASK_WEIGHT), 
				m_Faces[0]->GetMetrics()->GetRangeStart(),
				m_Faces[0]->GetMetrics()->GetRangeEnd()
			);

			if (!metrics) { return NULL; }

			match = CreateFace(m_Faces[0]->GetLoader(), metrics);
		}*/

		return match->GetHandle(a_Size, a_Style & FMASK_SETTINGS, a_Map);
	}

	Face* Family::CreateFace(Loader* a_Loader, Metrics* a_Metrics)
	{
		Face* result = new Face(m_Library, this);
		result->SetLoader(a_Loader);
		result->SetMetrics(a_Metrics);

		a_Metrics->SetFace(result);

		m_Faces.push_back(result);

		return result;
	}

	const tb::String& Family::GetName()
	{
		return m_Name;
	}

	Library* Family::GetLibrary()
	{
		return m_Library;
	}

	void Family::AddMetrics(Loader* a_Loader, Metrics* a_Metrics)
	{
		m_Metrics.push_back(a_Metrics);
	}

	FaceHandle* Family::CreateFontHandle(unsigned int a_Size, unsigned int a_Properties, CharMap* a_Map /*= NULL*/)
	{
		FaceHandle* result = NULL;

		for (size_t i = 0; i < m_Metrics.size(); i++)
		{
			result = m_Metrics[i]->CreateFace(a_Size, a_Properties, a_Map);
			if (result != NULL)
			{
				break;
			}
		}

		return result;
	}

}; // namespace Font